package com.yoso.starter.boot.util.file;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class AddWatermarkToWord {
    public static void main(String[] args) {
        String inputFilePath = "D:\\yoso\\dev\\temp\\1.docx"; // 输入文件路径
        String outputFilePath = "D:\\yoso\\dev\\temp\\2.docx"; // 输出文件路径
        String watermarkText = "Confidential"; // 水印文本

        try (FileInputStream fis = new FileInputStream(inputFilePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            // 创建一个新的段落作为水印
//            XWPFParagraph paragraph = document.createParagraph();

//
//            // 设置水印的透明度
//            run.getCTR().addNewRPr().addNewNoProof().setVal(true);
//            run.getCTR().addNewRPr().addNewVanish().setVal(true);

            // 将水印添加到页眉中
            XWPFHeaderFooterPolicy headerFooterPolicy = document.createHeaderFooterPolicy();
            XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
            XWPFParagraph paragraph = header.createParagraph();
            headerFooterPolicy.createWatermark(watermarkText);
            paragraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun run = paragraph.createRun();
            run.setText(watermarkText);
            run.setFontSize(50);
            run.setColor("D3D3D3"); // 设置字体颜色为灰色
            run.setSubscript(VerticalAlign.SUBSCRIPT); // 设置为下标
            // 保存修改后的文档
            try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
                document.write(fos);
            }

            System.out.println("水印已成功添加到文档中！");
        } catch (IOException  e) {
            e.printStackTrace();
        }
    }
}
